/*
 * wccli.c
 *
 *  Created on: Apr 1, 2012
 *      Author: root
 */


#include	"unp.h"

int
main(int argc, char **argv)
{
	int					sockfd;
	struct sockaddr_in	servaddr;

	if (argc != 2)
		err_quit("usage: tcpcli <IPaddress>");

	sockfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(5458);
	Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));

	str_cli(stdin, sockfd);		/* do it all */

	exit(0);
}

void
str_cli(FILE *fp, int sockfd)
{
	char	sendline[MAXLINE], recvline[MAXLINE];

	while (1) {
		fgets(sendline, MAXLINE, fp);
		if(sendline[0] == '.'){
			write(sockfd, sendline, strlen(sendline));
			read(sockfd, sendline, sizeof(sendline));
			printf("%s", sendline);
			close(sockfd);
			return;
		}
		else
			write(sockfd, sendline, strlen(sendline));

		if (read(sockfd, recvline, MAXLINE) == 0)
			err_quit("str_cli: server terminated prematurely");

		fputs(recvline, stdout);
	}
}
